define(['app', 'json2', 'ace-language-tools'], function(app, JSON2) {
    app.controller('JsonFormatterController', function($scope, $timeout) {
        var self = this;
        self.data = '';
        self.json = '';
        self.error = '';

        var jsonViewer = null;

        self.init = function() {
            self.data = '["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]';
            new Clipboard('#copy', {
                text: function() {
                    return jsonViewer.getValue();
                }
            });
            // json viewer
            $timeout(function() {
                jsonViewer = ace.edit('json-viewer');
                jsonViewer.getSession().setMode("ace/mode/json");
                jsonViewer.setOptions({
                    fontSize: 12,
                    showPrintMargin: false,
                    autoScrollEditorIntoView: true,
                    enableBasicAutocompletion: true,
                    enableSnippets: true,
                    enableLiveAutocompletion: true
                });
                $scope.$watch('vm.json', function(newValue) {
                    jsonViewer.setValue(newValue, -1);
                    jsonViewer.resize();
                });
            });
        }

        self.format = function(valid) {
            self.error = '';
            if (valid) {
                try {
                    self.json = JSON2.format(self.data, '\t');
                } catch (e) {
                    self.json = '';
                    self.error = e;
                }
            }
        }

        self.reset = function() {
            self.data = '';
            self.json = '';
            self.error = '';
        }
    });
});
